from pathlib import Path

from PySide6.QtCore import Qt
from PySide6.QtGui import QIntValidator, QFont, QResizeEvent

from ..base import ReturnView
from components import TableFrame
from qfluentwidgets import TitleLabel, LineEdit, LineEditButton, FluentIcon, PushButton, StateToolTip, InfoBar
import sys
from PySide6.QtWidgets import *
from typing import List, Any
from components import SliderFrame, ColorFrame, OpenFileDialog
from common import ImgAddMarkThread


class ImgAddMarkView(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._font = QFont('微软雅黑', 12)
        self.initUi()
        self.initLayout()

    def initUi(self):
        self.titleLabel = TitleLabel('图片加水印', self)
        self.tableFrame = TableFrame(self)
        self.tableFrame.setHeaders(['文件名称', '完整路径', '文件类型'])

        # 透明度控件
        self.opacitySlider = SliderFrame(self)
        self.opacitySlider.setText('透明度：')
        self.opacitySlider.setFixedHeight(30)
        self.opacitySlider.setValue(50)
        self.opacitySlider.setRange(0, 100)
        self.opacitySlider.setValidator()
        self.opacitySlider.setFont(self._font)

        # 颜色选择
        self.colorFrame = ColorFrame(self)
        self.colorFrame.setText('字体颜色：')
        self.colorFrame.setFixedHeight(30)
        self.colorFrame.setFont(self._font)

        # 字体大小
        self.fontFrame = SliderFrame(self)
        self.fontFrame.setText('字体尺寸：')
        self.fontFrame.setFixedHeight(30)
        self.fontFrame.setValue(13)
        self.fontFrame.setRange(0, 100)
        self.fontFrame.setValidator()
        self.fontFrame.setFont(self._font)

        # 文字间隔
        self.spaceSlider = SliderFrame(self)
        self.spaceSlider.setText('间距：')
        self.spaceSlider.setFixedHeight(30)
        self.spaceSlider.setValue(50)
        self.spaceSlider.setRange(0, 100)
        self.spaceSlider.setValidator()
        self.spaceSlider.setFont(self._font)

        # 倾斜角度
        self.angleSlider = SliderFrame(self, 360)
        self.angleSlider.setText('倾斜角度：')
        self.angleSlider.setFixedHeight(30)
        self.angleSlider.setValue(50)
        self.angleSlider.setRange(0, 360)
        self.angleSlider.setValidator(QIntValidator(0, 360, self.angleSlider))
        self.angleSlider.setFont(self._font)

        self.saveLineEdit = LineEdit()
        self.saveLineEdit.setClearButtonEnabled(True)
        self.saveLineEdit.setFixedHeight(30)
        self.saveLineEdit.setPlaceholderText('请选择保存文件夹')
        self.openFileButton = LineEditButton(FluentIcon.FOLDER, self.saveLineEdit)
        self.saveLineEdit.hBoxLayout.addWidget(self.openFileButton)
        self.saveLineEdit.setReadOnly(True)

        self.textLineEdit = LineEdit()
        self.textLineEdit.setPlaceholderText('请输入水印文字')
        self.textLineEdit.setFixedHeight(30)
        self.textLineEdit.setClearButtonEnabled(True)

        self.addButton = PushButton(FluentIcon.ADD, '添加文件', self)
        self.addButton.setMinimumSize(200, 30)
        self.startButton = PushButton('开始', self)
        # self.startButton.setFixedSize(400, 30)

        self.stateToolTip = StateToolTip('图片添加水印', '正在添加水印，请稍后...', self)
        self.stateToolTip.hide()
        self.imgAddMarkThread = ImgAddMarkThread(self)

        self.initEvent()

    def initEvent(self):
        # 按钮事件
        self.returnButton.clicked.connect(self.on_returButton_clicked)
        self.openFileButton.clicked.connect(self.on_openFileButton_clicked)
        self.addButton.clicked.connect(self.on_addButton_clicked)
        self.startButton.clicked.connect(self.on_startButton_clicked)
        # 线程事件
        self.imgAddMarkThread.started.connect(self.on_imgAddMarkThread_started)
        self.imgAddMarkThread.error.connect(self.on_imgAddMarkThread_error)
        self.imgAddMarkThread.progressed.connect(self.stateToolTip.setContent)
        self.imgAddMarkThread.finished.connect(self.on_imgAddMarkThread_finished)

    def initLayout(self):
        self.vBox.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignHCenter)
        self.vBox.addWidget(self.tableFrame)

        self.vBox.addWidget(self.opacitySlider)
        self.vBox.addWidget(self.colorFrame)
        self.vBox.addWidget(self.fontFrame)
        self.vBox.addWidget(self.spaceSlider)
        self.vBox.addWidget(self.angleSlider)
        hBox = self._addLayout([self.saveLineEdit, self.textLineEdit, self.addButton])
        self.vBox.addLayout(hBox)
        self.vBox.addWidget(self.startButton)

    def _addLayout(self, widgets: List) -> QHBoxLayout:
        hBox = QHBoxLayout()
        hBox.setContentsMargins(0, 0, 0, 0)
        hBox.setAlignment(Qt.AlignmentFlag.AlignLeft)
        for widget in widgets:
            hBox.addWidget(widget)
        return hBox

    def on_openFileButton_clicked(self):
        file = OpenFileDialog(self).getExistingDirectory()
        self.saveLineEdit.setText(file)

    def on_addButton_clicked(self):
        files = OpenFileDialog(self).getOpenFileNames(filter='图片(*.jpg;*.png;*.jpeg)')[0]
        for file in files:
            if file in self.tableFrame.getColumnValues(1):
                continue
            self.tableFrame.addItem([Path(file).stem, file, Path(file).suffix])

    def on_startButton_clicked(self):
        text = self.textLineEdit.text()
        col1 = self.tableFrame.getColumnValues(1)
        save_path = self.saveLineEdit.text()
        opacity = int(self.opacitySlider.value()) / 100
        color = self.colorFrame.color().name()
        fontSize = self.fontFrame.value()
        space = self.spaceSlider.value()
        angle = self.angleSlider.value()

        if text == '' or len(col1) == 0 or save_path == '':
            return

        self.imgAddMarkThread.set_value(
            text=text,
            img_files=col1,
            save_path=save_path,
            color=color,
            size=fontSize,
            opacity=opacity,
            space=space,
            angle=angle
        )
        self.imgAddMarkThread.start()

    def on_imgAddMarkThread_started(self):
        self.stateToolTip.show()

    def on_imgAddMarkThread_error(self, msg: str):
        InfoBar.error('错误', msg, duration=5000, parent=self)

    def on_imgAddMarkThread_finished(self):
        self.stateToolTip.hide()
        InfoBar.success('提示', '水印添加完毕', duration=3000, parent=self)

    def on_returButton_clicked(self):
        self.tableFrame.clear()
        self.saveLineEdit.clear()
        self.textLineEdit.clear()
        self.returned.emit()

    def resizeEvent(self, event: QResizeEvent):
        self.stateToolTip.move(event.size().width() - self.stateToolTip.width() - 20, 10)
        super().resizeEvent(event)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = ImgAddMarkView()
    win.resize(1000, 700)
    win.show()
    sys.exit(app.exec())
